package com.cat.model.web.interceptor;


import java.lang.reflect.Method;

import javax.servlet.http.HttpServletResponse;

import com.alonew.core.commons.page.AjaxObject;
import com.alonew.core.web.action.base.Struts2Action;
import com.alonew.core.web.util.ActionMethodUtil;
import com.alonew.core.web.util.ActionUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * post请求验证
 * 
 * @author penpen
 * 
 */
public class AdminInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 495254921117512933L;

	
	public String intercept(ActionInvocation ai) {
		
		Struts2Action action = (Struts2Action) ai.getAction();
        HttpServletResponse response = action.getServletResponse();
        Method method = ActionMethodUtil.getActionMethod(ai);
        try {
			return ai.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			if(method != null){
				processException(response, method, e);
			}
		}
        return null;
	}


	private void processException(HttpServletResponse response, Method method, Exception e) {
		response.setCharacterEncoding("utf-8");
		if(method.getName().contains("add") || method.getName().contains("edit")){
			ActionUtil.print(response,
					"<script>parent.callback(" + false + ", '"+e.getMessage()+"')</script>",
					"text/html; charset=utf-8");
		}else{
			ActionUtil.print(response,
					AjaxObject.newOk("操作失败！"+ e.getMessage()).setCallbackType("").toString() ,
					"application/json; charset=utf-8");
		}
	}
}
